package com.dong.designpattern.singleton;

/**
 * 单例模式 - 懒汉式5（lazy loading）
 * 更完美的写法（比Singleton06更完美，Singleton06还是有点小毛病的）：静态内部类方式
 * JVM保证单例
 * 加载外部类时不会加载内部类，这样可以实现懒加载（而Singleton01不能保证懒加载）
 *
 * @author by jiweidong on 2021/11/16.
 */
public class Singleton07 {

    private static Singleton07 INSTANCE;

    private Singleton07() {

    }

    private static class Singleton07Holder {
        private final static Singleton07 INSTANCE = new Singleton07();
    }

    public static Singleton07 getInstance() throws InterruptedException {
        return Singleton07Holder.INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Singleton07.getInstance().hashCode());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
